#include "Json.h"

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <list>
#include <map>
#include <iomanip>

using namespace std;

Json::Json()
{
    type = JNULL_t;
    addr = nullptr;
}
Json::Json(int val) : Json(double(val))
{
}
Json::Json(double val)
{
    type = JNUM_t;
    addr = new double(val);
}
Json::Json(bool val)
{
    type = JBOOL_t;
    addr = new bool(val);
}
Json::Json(string val)
{
    type = JSTRING_t;
    addr = new string(val);
}
Json::Json(const char *str) : Json(string(str))
{
}

string Json::to_string()
{
    Json *js = this;
    stringstream ss;
    if (js->type == Json::JNUM_t)
    {
        double *num = (double *)js->addr;
        ss.setf(std::ios::fixed);
        ss.precision(2);
        ss << *num;
    }
    else if (js->type == Json::JBOOL_t)
    {
        bool *num = (bool *)js->addr;
        if( *num )
            ss << "true";
        else 
            ss <<"false";
    }
    else if (js->type == Json::JNULL_t)
    {
        ss <<"null";
    }
    else if (js->type == Json::JSTRING_t)
    {
        string *num = (string *)js->addr;
        ss << '"' << *num << '"';
    }
    else if (js->type == Json::JARRAY_t)
    {
        vector<Json *> *arr = (vector<Json *> *)js->addr;
        ss << "[";
        for (int i = 0; i < (*arr).size(); i++)
        {
            ss << ((*arr)[i])->to_string();
            if (i != (*arr).size() - 1)
                ss << ", ";
        }
        ss << "]";
    }
    else if (js->type == Json::JOBJECT_t)
    {
        // map<string, Json*> keys; //object拥有的keys
        map<string, Json *> *keys = (map<string, Json *> *)js->addr;
        ss << "{"; 
        for (auto it = keys->begin(); it != keys->end();  )
        {
            ss << '"' << it->first << "\": ";
            ss << (it->second)->to_string();
            if (++it != keys->end() ){
                ss << ", ";
            }
                
        }
        ss << "}";
    }
    return ss.str();
}
// 按类型析构 需要递归
Json::~Json(){
    Json *js = this;
    if (js->type == Json::JNUM_t)
    {
        double *num = (double *)js->addr;
        delete num;
    }
    else if (js->type == Json::JBOOL_t)
    {
        bool *num = (bool *)js->addr;
        delete num;
    }
    else if (js->type == Json::JNULL_t)
    {
         
    }
    else if (js->type == Json::JSTRING_t)
    {
        string *num = (string *)js->addr;
        delete num;
         
    }
    else if (js->type == Json::JARRAY_t)
    {
        vector<Json *> *arr = (vector<Json *> *)js->addr;
        for (Json* ptr : *arr)
        {
            delete ptr;
        }
    }
    else if (js->type == Json::JOBJECT_t)
    {
        // map<string, Json*> keys; //object拥有的keys
        map<string, Json *> *keys = (map<string, Json *> *)js->addr;
        for(auto it : *keys){
            delete it.second;
        } 
    }
    // cout << "~Json()" << endl;
}
